/**
一定要记得在confin.json配置这个模块的参数,否则无法使用
*/
package user

import (
	"github.com/liangdas/mqant/conf"
	"github.com/liangdas/mqant/module"
	"github.com/liangdas/mqant/module/base"
	"model/user"
	"utils"
	"github.com/liangdas/mqant/gate"
	"model"
	"fmt"
	"time"
	"github.com/bradfitz/gomemcache/memcache"
	"strconv"
	"encoding/json"
	"model/gamelog"
	"github.com/satori/go.uuid"
	"github.com/liangdas/mqant/log"
	"utils/cfg"

	//"github.com/garyburd/redigo/redis"
	"model/config"
)
var Module = func() module.Module {
	user := new(User)
	return user
}
type User struct {
	basemodule.BaseModule
}
func (u *User) GetType() string {
	//很关键,需要与配置文件中的Module配置对应
	return "User"
}
func (u *User) Version() string {
	//可以在监控时了解代码版本
	return "1.0.0"
}
func (u *User) OnInit(app module.App, settings *conf.ModuleSettings) {
	//初始化模块
	u.BaseModule.OnInit(u, app, settings)
	u.GetServer().RegisterGO("isPossess", u.isPossess)
	u.GetServer().RegisterGO("deleteSeed", u.deleteSeed)
	u.GetServer().RegisterGO("useEnergy", u.useEnergy)
	u.GetServer().RegisterGO("waterChance", u.waterChance)
	u.GetServer().RegisterGO("updateExp", u.updateExp)
	//注册远程调用的函数
	u.GetServer().RegisterGO("HD_UserDepotList", u.userDepotList) //我们约定所有对客户端的请求都以Handler_开头
	u.GetServer().RegisterGO("HD_UserGmList", u.userGmList) //我们约定所有对客户端的请求都以Handler_开头
	u.GetServer().RegisterGO("HD_ChartList", u.chartList) //我们约定所有对客户端的请求都以Handler_开头
	u.GetServer().RegisterGO("HD_EditContact", u.editContact) //我们约定所有对客户端的请求都以Handler_开头
	u.GetServer().RegisterGO("HD_DeleteContact", u.deleteContact) //我们约定所有对客户端的请求都以Handler_开头
	u.GetServer().RegisterGO("HD_ContactList", u.contactList) //我们约定所有对客户端的请求都以Handler_开头
	u.GetServer().RegisterGO("HD_GetCharListVersion", u.getCharListVersion) //我们约定所有对客户端的请求都以Handler_开头
	u.GetServer().RegisterGO("HD_GetGmListVersion", u.getGmListVersion) //我们约定所有对客户端的请求都以Handler_开头
	u.GetServer().RegisterGO("HD_DeliverList", u.deliverList) //我们约定所有对客户端的请求都以Handler_开头
	u.GetServer().RegisterGO("HD_ApplyDeliver", u.applyDeliver) //我们约定所有对客户端的请求都以Handler_开头
	u.GetServer().RegisterGO("HD_UserSign", u.userSign) //我们约定所有对客户端的请求都以Handler_开头
	u.GetServer().RegisterGO("HD_GmList", u.gmlist) //我们约定所有对客户端的请求都以Handler_开头
	u.GetServer().RegisterGO("HD_UserGmTest", u.userGmTest) //我们约定所有对客户端的请求都以Handler_开头
	u.GetServer().RegisterGO("HD_DeleteGm", u.deleteGm) //我们约定所有对客户端的请求都以Handler_开头
	u.GetServer().RegisterGO("HD_AddGm", u.addGm) //我们约定所有对客户端的请求都以Handler_开头
	u.GetServer().RegisterGO("HD_SignList", u.signList) //我们约定所有对客户端的请求都以Handler_开头
}

func (u *User) userGmTest(session gate.Session, msg map[string]interface{}) {
	//areaId:=msg["areaId"].(float64)
	userId:=msg["userId"].(float64)
	redisData:=*utils.GetRedisData(userId)
	exp :=redisData["exp"].(float64)+1
	redisData["exp"] = exp
	utils.SetRedisData(userId,redisData)

}
func (u *User) Run(closeSig chan bool) {
	//运行模块
}
func (u *User) OnDestroy() {
	//注销模块
	//一定别忘了BaseModule.OnDestroy()
	u.BaseModule.OnDestroy()
}
//用户仓库列表
func (u *User) userDepotList(session gate.Session, msg map[string]interface{})(result map[string]interface{}, err string) {
	var userDb = model.DB("FarmUser")
	defer userDb.Close()
	areaId := msg["areaId"]
	userId := msg["userId"]
	dType := msg["type"]
	if userId==nil{
		err = "userId未知"
		return nil,err
	}
	if areaId==nil{
		err = "areaId未知"
		return nil,err
	}
	if dType==nil{
		err = "dType未知"
		return nil,err
	}
	var results []user.UserDepotResult
	var userDepot []user.UserDepot
	sort:="id desc"
	var prepage int8=6;
	var page int8=0;
	where:=map[string]interface{}{"userId": userId,"areaId": areaId,"dType":dType}
	selectStr:="id,propId,propName,propNum,dType,sType"
	ds:=utils.GetPageList(userDb,&results,&userDepot,selectStr,where,sort,prepage,page,"user_depot",true)
	return ds,""
}
//用户是否有当前种子
func (u *User) isPossess(msg map[string]interface{})(result int8, err string)  {
	id:=msg["dId"]
	userId:=msg["userId"]
	areaId:=msg["areaId"]
	var userDb = model.DB("FarmUser")
	defer userDb.Close()
	var userDepot user.UserDepot
	rowNum:=userDb.Where(map[string]interface{}{"id": id,"dType": 0,"userId":userId,"areaId":areaId}).First(&userDepot).Error
	if rowNum!=nil{
		return 4,"没有当前种子"
	}
	return userDepot.SType,""
}

//获取好友列表版本
func (u *User) getGmListVersion(session gate.Session, msg map[string]interface{}) (version string, err string){
	areaId:= msg["areaId"].(float64)
	userId:= msg["userId"].(float64)
	_areaId:=strconv.FormatInt(int64(areaId), 10)
	_userId:=strconv.FormatInt(int64(userId), 10)
	mc := memcache.New(utils.MemcacheServer)
	curTime := time.Now()
	timestamp := strconv.FormatInt(curTime.UTC().UnixNano(), 10)
	curTimeStr := timestamp[:10]
	nextTime:=utils.NextTime() //获取明天0点
	curTimeInt, _ := strconv.ParseInt(curTimeStr, 10, 64)
	timeLine:=nextTime-curTimeInt //时差时间戳
	if mc == nil {
		fmt.Println("memcache New failed")
	}
	versionStr := fmt.Sprintf("farmGmVersion-%s-%s", _areaId,_userId)
	fmt.Println(versionStr)
	item,_:=mc.Get(versionStr)
	if item == nil{
		version = curTimeStr
		err:=mc.Set(&memcache.Item{Key:versionStr, Value: []byte(version),Expiration:int32(timeLine)})
		if err!=nil{
			panic(err)
		}
	}else{
		version = string(item.Value)
	}
	return version,""
}
//好友列表
func (u *User) userGmList(session gate.Session, msg map[string]interface{})(result map[string]interface{}, err string) {
		areaId:=msg["areaId"].(float64)
		userId:=msg["userId"].(float64)
		fmt.Println("没有数据 去查找")
		//去查询数据
		var userDb = model.DB("FarmUser")
		defer userDb.Close()
		var gm user.UserGm
		where:=map[string]interface{}{"areaId":areaId,"userId":userId}
		userDb.Select("fans").Where(where).First(&gm)
		var m []uint
		json.Unmarshal(*gm.Fans,&m)
		ds := make(map[string]interface{}, 50)
		d := make(map[string]interface{}, 50)
		for k,v:= range m{
			redisData:=*utils.GetRedisData(float64(v))
			i:=strconv.Itoa(k)
			d[i] = redisData
			redisData["TimeStr"] = utils.PutTime(int64(redisData["lastLoginTime"].(float64)))
			fmt.Println(redisData)
		}
		ds["list"] = d
		fmt.Println(ds)
		//b,_:= json.Marshal(result)
	return ds,""
}



//好友列表
//func (u *User) userGmList(session gate.Session, msg map[string]interface{})(result map[string]interface{}, err string) {
//	areaId:=msg["areaId"].(float64)
//	userId:=msg["userId"].(float64)
//	var version string
//	if msg["version"] == nil{
//		version = ""
//	}else{
//		version = msg["version"].(string)
//	}
//	mc := memcache.New(utils.MemcacheServer)
//	if mc == nil {
//		fmt.Println("memcache New failed")
//	}
//	curTime := time.Now()
//	timestamp := strconv.FormatInt(curTime.UTC().UnixNano(), 10)
//	curTimeStr := timestamp[:10]
//	nextTime:=utils.NextTime() //获取明天0点
//	curTimeInt, _ := strconv.ParseInt(curTimeStr, 10, 64)
//	timeLine:=nextTime-curTimeInt //时差时间戳
//	_areaId:=strconv.FormatInt(int64(areaId), 10)
//	_userId:=strconv.FormatInt(int64(userId), 10)
//	var versionStr string
//	if version == ""{
//		versionStr = fmt.Sprintf("farmGmVersion-%s-%s", _areaId,_userId)
//		item,_:=mc.Get(versionStr)
//		if item == nil{
//			version = curTimeStr
//			mc.Set(&memcache.Item{Key:versionStr, Value: []byte(version),Expiration:int32(timeLine)})
//		}else{
//			version = string(item.Value)
//		}
//	}
//	chartListStr := fmt.Sprintf("farmGmList-%s-%s-%s", _areaId,_userId,version)
//	chartListKey:=utils.Md5(chartListStr)
//	charItem,_:=mc.Get(chartListKey)
//	if charItem==nil{
//		fmt.Println("没有数据 去查找")
//		//去查询数据
//		var userDb = model.DB("FarmUser")
//		defer userDb.Close()
//		var gm user.UserGm
//		where:=map[string]interface{}{"areaId":areaId,"userId":userId}
//		userDb.Select("fans").Where(where).First(&gm)
//		var m []uint
//		json.Unmarshal(*gm.Fans,&m)
//		var users user.GameUser
//		var usersResult []user.GameUserResult
//		var userWealth user.UserWealth
//		var userWealthResult []user.UserWealthResult
//		userDb.Where("userId in (?)", m).Find(&users).Order("userId desc").Scan(&usersResult)
//		userDb.Where("userId in (?)", m).Find(&userWealth).Order("userId desc").Scan(&userWealthResult)
//		for k,_:= range usersResult{
//			usersResult[k].Exp = userWealthResult[k].Exp
//			usersResult[k].TimeStr = utils.PutTime(usersResult[k].LastLoginTime)
//		}
//		result = utils.IToMap(usersResult)
//		b,_:= json.Marshal(result)
//		err:=mc.Set(&memcache.Item{Key:chartListKey, Value:[]byte(b),Expiration:int32(timeLine)})
//		if err!=nil{
//			panic(err)
//		}
//	}else{
//		fmt.Println("有数据")
//		json.Unmarshal(charItem.Value,&result)
//	}
//	return result,""
//
//}
//用户地址列表
func (u *User) contactList(session gate.Session, msg map[string]interface{})(result map[string]interface{}, err string){
	var userDb = model.DB("FarmUser")
	defer userDb.Close()
	areaId:=msg["areaId"]
	userId:=msg["userId"]
	node:=msg["node"].(float64)
	fmt.Println(node)
	if node == float64(1){
		var UserContact []user.UserContact
		var UserContactResults []user.UserContactResult
		sort:="id desc"
		var prepage int8=6
		var page int8=0
		where:=map[string]interface{}{"areaId":areaId,"userId":userId}
		selectStr:="id,userName,province,city,area,address,phoneNum,choice"
		ds:=utils.GetPageList(userDb,&UserContactResults,&UserContact,selectStr,where,sort,prepage,page,"user_contact",true)
		return ds,""
	}else{

		var UserContact user.UserContact
		var UserContactResults user.UserContactResult
		where:=map[string]interface{}{"areaId":areaId,"userId":userId,"choice":0}
		userDb.Where(where).First(&UserContact).Scan(&UserContactResults)
		ds := utils.Struct2Map(UserContactResults)
		return ds,""
	}

}
//编辑地址
func (u *User) editContact(session gate.Session, msg map[string]interface{})(result bool, err string) {
	var userDb = model.DB("FarmUser")
	defer userDb.Close()
	fmt.Println(msg)
	id:=msg["id"].(float64)
	areaId:=msg["areaId"].(float64)
	userId:=msg["userId"].(float64)
	userName:=msg["userName"].(string)
	province:=msg["province"].(string)
	city:=msg["city"].(string)
	area:=msg["area"].(string)
	address:=msg["address"].(string)
	phoneNum:=msg["phoneNum"].(string)
	choice:=msg["choice"].(float64)
	createTime:=time.Now()
	updateTime:=time.Now()
	if id>0{
		var contact user.UserContact
		//修改地址
		where:=map[string]interface{}{"areaId":areaId,"userId":userId,"id":id}
		if err:=userDb.Where(where).First(&contact).Error;err!=nil{
			panic(err)
		}
		m:=map[string]interface{}{
			"userName":userName,
			"province":province,
			"city":city,
			"area":area,
			"address":address,
			"phoneNum":phoneNum,
			"choice":choice,
			"updateTime":time.Now(),
			}
		if err:=userDb.Model(&contact).Updates(m).Error;err!=nil{
			panic(err)
		}
		return true,""
	}else{
		contact:=&user.UserContact{
			AreaId:uint(areaId),
			UserId:uint(userId),
			UserName:userName,
			Province:province,
			City:city,
			Area:area,
			Address:address,
			PhoneNum:phoneNum,
			Choice:int8(choice),
			CreateTime:createTime,
			UpdateTime:updateTime,
		}
		if err:=userDb.Create(&contact).Error;err!=nil{
			panic(err)
		}
		return true,""
	}
}
//删除地址
func (u *User) deleteContact(session gate.Session, msg map[string]interface{}) (result bool, err string){
	var userDb = model.DB("FarmUser")
	id:=msg["id"]
	areaId:=msg["areaId"]
	userId:=msg["userId"]
	defer userDb.Close()
	var userContact user.UserContact
	where:=map[string]interface{}{"areaId":areaId,"id":id,"userId":userId}
	if err:=userDb.Where(where).First(&userContact).Error;err!=nil{
		panic(err)
	}
	if err:=userDb.Delete(&userContact).Error;err!=nil{
		panic(err)
	}else{
		return true,""
	}
}

//获取排行榜版本
func (u *User) getCharListVersion(session gate.Session, msg map[string]interface{}) (version string, err string){
	areaId:= msg["areaId"].(float64)
	var userId float64
	utype := msg["type"].(float64)
	userId = msg["userId"].(float64)
	_areaId:=strconv.FormatInt(int64(areaId), 10)
	_utype:=strconv.FormatInt(int64(utype), 10)
	_userId:=strconv.FormatInt(int64(userId), 10)
	mc := memcache.New(utils.MemcacheServer)
	curTime := time.Now()
	timestamp := strconv.FormatInt(curTime.UTC().UnixNano(), 10)
	curTimeStr := timestamp[:10]
	nextTime:=utils.NextTime() //获取明天0点
	curTimeInt, _ := strconv.ParseInt(curTimeStr, 10, 64)
	timeLine:=nextTime-curTimeInt //时差时间戳
	if mc == nil {
		fmt.Println("memcache New failed")
	}
	versionStr := fmt.Sprintf("farmChartVersion-%s-%s-%s", _areaId,_userId,_utype)
	fmt.Println(versionStr)
	item,_:=mc.Get(versionStr)
	if item == nil{
		version = curTimeStr
		err:=mc.Set(&memcache.Item{Key:versionStr, Value: []byte(version),Expiration:int32(timeLine)})
		if err!=nil{
			panic(err)
		}
	}else{
		version = string(item.Value)
	}
	return version,""
}

//排行榜
func (u *User) chartList(session gate.Session, msg map[string]interface{}) (result map[string]interface{}, err string){
	areaId:=msg["areaId"].(float64)
	var userId float64
	utype := msg["type"].(float64)
	userId = msg["userId"].(float64)
	var version string
	if msg["version"] == nil{
		version = ""
	}else{
		version = msg["version"].(string)
	}
	mc := memcache.New(utils.MemcacheServer)
	if mc == nil {
		fmt.Println("memcache New failed")
	}
	curTime := time.Now()
	timestamp := strconv.FormatInt(curTime.UTC().UnixNano(), 10)
	curTimeStr := timestamp[:10]
	nextTime:=utils.NextTime() //获取明天0点
	curTimeInt, _ := strconv.ParseInt(curTimeStr, 10, 64)
	timeLine:=nextTime-curTimeInt //时差时间戳
	_areaId:=strconv.FormatInt(int64(areaId), 10)

	_userId:=strconv.FormatInt(int64(userId), 10)

	_utype:=strconv.FormatInt(int64(utype), 10)

	var versionStr string
	if version == ""{
		versionStr = fmt.Sprintf("farmChartVersion-%s-%s-%s", _areaId,_userId,_utype)
		item,_:=mc.Get(versionStr)
		if item == nil{
			version = curTimeStr
			mc.Set(&memcache.Item{Key:versionStr, Value: []byte(version),Expiration:int32(timeLine)})
		}else{
			version = string(item.Value)
		}
	}
	chartListStr := fmt.Sprintf("farmChartList-%s-%s,%s,%s", _areaId,_userId,version,_utype)
	chartListKey:=utils.Md5(chartListStr)
	charItem,_:=mc.Get(chartListKey)
	if charItem==nil{
		fmt.Println("没有数据 去查找")
		//去查询数据
		var userDb = model.DB("FarmUser")
		defer userDb.Close()
		var results []user.ChartResult
		var wealth []user.UserWealth
		selectStr:="nickname,head,exp,userId"
		where:=map[string]interface{}{"areaId":areaId}
		sort:="exp desc"
		var prepage int8=50
		var page int8=0
		var m []uint = nil
		if utype>0{
			var gm user.UserGm
			wher:=map[string]interface{}{"areaId":areaId,"userId":userId}
			userDb.Select("fans").Where(wher).First(&gm)
			json.Unmarshal(*gm.Fans,&m)
			m = append(m, uint(userId))
			userDb.Select(selectStr).Where("userId in (?)",m).Order(sort).Offset(page*prepage).Limit(prepage).Find(&wealth).Scan(&results)
			d :=utils.IToMap(results)
			fmt.Println(d)
			ds := make(map[string]interface{}, prepage)
			ds["list"] = d
			result = ds
			l:=result["list"].(map[string]interface{})
			result["myIndex"] = 0
			//fmt.Println(result)
			for k,_:=range l{
				index,_:=strconv.Atoi(k)

				ll:=l[k].(map[string]interface{})
				ll["Index"] = index+1

				if float64(ll["UserId"].(uint))==float64(userId){
					result["myIndex"] = ll["Index"]
				}
			}
		}else{
			result = utils.GetPageList(userDb,&results,&wealth,selectStr,where,sort,prepage,page,"user_wealth",false)
			l:=result["list"].(map[string]interface{})
			result["myIndex"] = 0
			for k,_:=range l{
				index,_:=strconv.Atoi(k)
				ll:=l[k].(map[string]interface{})
				ll["Index"] = index+1
				a:=float64(ll["UserId"].(uint))
				b:=float64(userId)
				if(a==b){
					result["myIndex"] = ll["Index"]
				}
			}
		}

		b,_:= json.Marshal(result)
		err:=mc.Set(&memcache.Item{Key:chartListKey, Value:[]byte(b),Expiration:int32(timeLine)})
		if err!=nil{
			panic(err)
		}
	}else{
		fmt.Println("有数据")
		json.Unmarshal(charItem.Value,&result)
	}
	return result,""
}
//deleteSeed
func (u User) deleteSeed(msg map[string]interface{})(result bool, err string){
	id:=msg["dId"]
	userId:=msg["userId"]
	areaId:=msg["areaId"]
	var userDb = model.DB("FarmUser")
	defer userDb.Close()
	var userDepot user.UserDepot
	userDb.Where(map[string]interface{}{"id": id,"dType": 0,"userId":userId,"areaId":areaId}).First(&userDepot)
	if userDepot.PropNum >1{
		userDepot.PropNum -= 1
		if err:=userDb.Save(&userDepot).Error;err!=nil{
			return false,"移除种子失败"
		}else{
			return true,""
		}
	}else{
		err:=userDb.Where(map[string]interface{}{"id": id,"dType": 0,"userId":userId,"areaId":areaId}).Delete(&userDepot).Error
		if err!=nil{
			return true,""
		}
	}
	return false,"移除种子失败"
}
func (u *User) useEnergy(msg map[string]interface{})(result bool, err string) {
	energy:=float64(1)
	userId:=msg["userId"].(float64)
	areaId:=msg["areaId"].(float64)
	var userDb = model.DB("FarmUser")
	defer userDb.Close()
	var userWealth user.UserWealth
	where := map[string]interface{}{"userId": userId, "areaId": areaId}
	userDb.Where(where).First(&userWealth);
	if userWealth.Energy>=energy{
		e:=userWealth.Energy-energy
		userDb.Model(&userWealth).Where(where).Update(map[string]interface{}{"energy": e})
		return true,""
	}else{
		return false,"能量不够"
	}
}
func (u *User) waterChance(msg map[string]interface{})(result map[string]interface{}, err string) {
	userId:=msg["userId"].(float64)
	areaId:=msg["areaId"].(float64)
	var userDb = model.DB("FarmUser")
	defer userDb.Close()
	var userWealth user.UserWealth
	var userWaterResult user.UserWaterResult

	where := map[string]interface{}{"userId": userId, "areaId": areaId}
	if err:=userDb.Select("selfWater,otherWater,receiveCount,giveCount").Where(where).First(&userWealth).Scan(&userWaterResult).Error;err!=nil{
		panic(err)
	}
	fmt.Println(userWaterResult)
	result = utils.Struct2Map(userWaterResult)
	fmt.Println(result)
	return
}
func (u *User) updateExp(msg map[string]interface{})(result bool, err string) {
	exp:=msg["exp"].(float64)
	userId:=msg["userId"].(float64)
	areaId:=msg["areaId"].(float64)
	var userDb = model.DB("FarmUser")
	defer userDb.Close()
	var userWealth user.UserWealth
	where := map[string]interface{}{"areaId": areaId,"userId": userId}
	if err:=userDb.Where(where).First(&userWealth).Error;err!=nil{
		return false,"没有找到该用户"
	}
	e:=userWealth.Exp + int32(exp)
	userDb.Model(&userWealth).Where(where).Update("exp", e)
	redisData:=*utils.GetRedisData(userId)
	redisData["exp"] = e
	utils.SetRedisData(userId,redisData)
	return true,""
}
//物流列表
func (u *User) deliverList(session gate.Session,msg map[string]interface{})(result map[string]interface{}, err string) {
	userId:=msg["userId"].(float64)
	areaId:=msg["areaId"].(float64)
	var logDb = model.DB("FarmLog")
	defer logDb.Close()
	var shops []gamelog.DeliverLog
	var results []gamelog.DeliverResult
	sort:="orderDate desc"
	var prepage int8=6
	var page int8=0
	where:=map[string]interface{}{"areaId":areaId,"userId":userId}
	selectStr:="orderId,packMsg,packNum,status,orderDate"
	ds:=utils.GetPageList(logDb,&results,&shops,selectStr,where,sort,prepage,page,"deliver_log",true)
	return ds,""
}
//func deliver(data map[string]interface{},areaId float64,userId float64,propMsg string,packNum int) bool{
//	var logDb = model.DB("FarmLog")
//	defer logDb.Close()
//	uuid := uuid.Must(uuid.NewV4())
//	OrderId:=uuid.String()
//	fmt.Println(OrderId)
//	PackData,e:=json.Marshal(data)
//	if e!=nil{
//		panic(e)
//	}
//	var deliverLog = &gamelog.DeliverLog{
//		OrderId:OrderId,
//		AreaId:uint(areaId),
//		UserId:uint(userId),
//		PackMsg:propMsg,
//		PackData:&PackData,
//		PackNum:int8(packNum),
//		Status:0,
//		OrderDate:time.Now(),
//	}
//	if err:=logDb.Create(&deliverLog).Error;err!=nil{
//		fmt.Println(err)
//		return false
//	}else{
//		return true
//	}
//}
//申请发货
func (u *User) applyDeliver(session gate.Session,msg map[string]interface{})(result bool, err string) {
	fmt.Println(msg)
	log.Debug("msg:",msg)
	var logDb = model.DB("FarmLog")
	var userDb = model.DB("FarmUser")
	defer logDb.Close()
	userId:=msg["userId"].(float64)
	areaId:=msg["areaId"].(float64)
	if msg["deliverData"] == nil{
		return false,"没有植物信息"
	}
	deliverData:=msg["deliverData"].([]interface {})

	data:=utils.IToMap2(deliverData)
	var sType1Num float64
	var propMsg string
	var packNum int = len(data)
	var propTotalNum float64
	var index int = 0

	for _,v:=range data{
		index++
		var depot user.UserDepot
		ass:=v.(map[string]interface {})
		propName:=ass["propName"].(string)
		propNum:=ass["propNum"].(float64)
		propId:=ass["propId"].(float64)
		fmt.Println(propId,propNum)
		where:=map[string]interface{}{"propId": propId,"userId":userId,"areaId":areaId,"dType":1}
		if err:=userDb.Model(&depot).Where(where).Find(&depot).Error;err!=nil{
			return false,"没有找到相关植物"
		}
		if depot.SType==0&&propNum!=12{
			return false,"鲜花需要单品数量12个才能申请发货"
		}

		if depot.SType==1{
			sType1Num+=propNum
		}
		if index == packNum{

			if sType1Num <5{
				return false,"多肉需要5个才能申请发货"
			}
		}
		fmt.Println(depot)
		//删除发货植物
		if(depot.PropNum==int16(propNum)){
			userDb.Delete(&depot)
		}else if depot.PropNum>int16(propNum) {
			c:=depot.PropNum-int16(propNum)
			userDb.Model(&depot).Where(where).Update(map[string]interface{}{"propNum": c})
		}else{
			return false,"植物数量不够"
		}
		propNumString:=strconv.FormatInt(int64(propNum),10)
		propMsg += propName+"×"+propNumString
		propTotalNum+=propNum
	}
	//if propTotalNum ==float64(0){
	//	return false,"申请发货失败"
	//}
	uuid := uuid.Must(uuid.NewV4())
	OrderId:=uuid.String()
	fmt.Println(OrderId)
	PackData,e:=json.Marshal(data)
	if e!=nil{
		panic(e)
	}
	var deliverLog = &gamelog.DeliverLog{
		OrderId:OrderId,
		AreaId:uint(areaId),
		UserId:uint(userId),
		PackMsg:propMsg,
		PackData:&PackData,
		PackNum:int8(propTotalNum),
		Status:0,
		OrderDate:time.Now(),
	}
	if err:=logDb.Create(&deliverLog).Error;err!=nil{
		fmt.Println(err)
		return false,"申请发货失败"
	}else{
		return true,""
	}
}
/*
	1.判断用户签到日志是否存在
	2.存在 判断今天是否签到 /没有 判断 昨天是否签到
	3.昨天签到则继续今天的签到+1天 /昨天没签则重新签到列表 第一天开始
	4.签到完成 奖励发送
*/

////用户签到
func (u *User) userSign(session gate.Session,msg map[string]interface{})(result bool, err string) {
	userId:=msg["userId"].(float64)
	areaId:=msg["areaId"].(float64)
	nickname:=msg["nickname"].(string)
	var logDb = model.DB("FarmLog")
	var signLog gamelog.LogSign
	var ip string = session.GetIP()
	var userDb = model.DB("FarmUser")
	var userWealth user.UserWealth

	where:=map[string]interface{}{"userId":userId,"areaId":areaId}
	if err:=logDb.Where(where).First(&signLog).Error;err!=nil{
		log.Debug("没有签到信息",err)
		//创建
		signLog = gamelog.LogSign{
			UserId:uint(userId),
			AreaId:uint(areaId),
			Nickname:nickname,
			SignDate:time.Now(),
			Ip:ip,
			Status:0,
		}
		if err:=logDb.Create(&signLog).Error;err!=nil{
			log.Debug("创建失败",err)
		}
	}
	nTime := time.Now()
	curTime:=nTime.Format("20060102")
	yesTime := nTime.AddDate(0,0,-1)
	signDate := yesTime.Format("20060102")
	awardCnf:= cfg.Sign["AwardCnf"].(map[string]int)
	where2:=map[string]interface{}{"userId":userId,"areaId":areaId,"signDate":signDate}
	if err:=logDb.Where(where2).First(&signLog).Error;err!=nil{
		where:=map[string]interface{}{"userId":userId,"areaId":areaId,"signDate":curTime}
		if err:=logDb.Where(where).First(&signLog).Error;err!=nil{
			log.Debug("昨天没有签到",err)
			//从头开始
			if err:=logDb.Model(&signLog).Update(map[string]interface{}{"times":1,"signDate":time.Now()}).Error;err!=nil{
				log.Debug("重置签到日志失败",err)
			}
			//派发奖励
			userDb.Where(map[string]interface{}{"userId":userId,"areaId":areaId}).First(&userWealth)

			indexNum:=awardCnf["1"]
			energy:=userWealth.Energy+float64(indexNum)
			where:=map[string]interface{}{"userId":userId,"areaId":areaId}
			if err:=userDb.Model(&userWealth).Where(where).Update(map[string]interface{}{"energy":energy}).Error;err!=nil{
				logDb.Model(&signLog).Update(map[string]interface{}{"times":1,"signDate":time.Now(),"desc":"奖励阳光2个","status":-2,"msg":"奖励发送失败"})
				return false,"奖励发送失败"
			}
			energystr:=strconv.Itoa(indexNum)
			desc:="奖励阳光"+energystr+"个"
			logDb.Model(&signLog).Update(map[string]interface{}{"times":1,"signDate":time.Now(),"desc":desc,"status":1,"msg":"奖励发送成功"})
			return true,""
		}else{
			return false,"今天已经签到"
		}

	}else{
		log.Debug("昨天有签到",err)
		where:=map[string]interface{}{"userId":userId,"areaId":areaId,"signDate":curTime}
		//今天没签到
		if err:=logDb.Where(where).First(&signLog).Error;err!=nil{
			day:=signLog.Times+int8(1)
			//奖励派送
			if day==int8(8){
				day = 1
			}
			var desc string
			var gain float64 = 0
			switch day {
			case int8(3):
				if gain<float64(1){
					desc="奖励吉娃娃2个"
				}
				result,er:=send(day,areaId,userId,1)
				if er!=""{
					fmt.Println(result)
					if err:=logDb.Model(&signLog).Update(map[string]interface{}{"times":day,"signDate":time.Now(),"desc":desc,"status":-2,"msg":"奖励发送失败"}).Error;err!=nil{
						log.Debug("修改签到日志失败",err)
					}
					return false,er
				}
				gain=float64(1)
			case int8(7):
				if gain<float64(2){
					desc="奖励白牡丹2个"
				}
				result,er:=send(day,areaId,userId,1)
				if er!=""{
					fmt.Println(result)
					if err:=logDb.Model(&signLog).Update(map[string]interface{}{"times":day,"signDate":time.Now(),"desc":desc,"status":-2,"msg":"奖励发送失败"}).Error;err!=nil{
						log.Debug("修改签到日志失败",err)
					}
					return false,er
				}
				gain = float64(2)
			default:
				result,er:=send(day,areaId,userId,0)
				if er!=""{
					fmt.Println(result)
					if err:=logDb.Model(&signLog).Update(map[string]interface{}{"times":day,"signDate":time.Now(),"desc":desc,"status":-2,"msg":"奖励发送失败"}).Error;err!=nil{
						log.Debug("修改签到日志失败",err)
					}
					return false,er
				}
				desc="奖励阳光2个"
			}
			logDb.Model(&signLog).Update(map[string]interface{}{"times":day,"signDate":time.Now(),"desc":desc,"gain":gain,"status":1,"msg":"奖励发送完成"})
			return true,""
			}
			return false,"今天已经签到"
		}
}
func send(day int8,areaId float64,userId float64,sendType int8) (result bool,err string){
	dayIndex:=strconv.Itoa(int(day))
	var userWealth user.UserWealth
	var userDb = model.DB("FarmUser")
	awardCnf:= cfg.Sign["AwardCnf"].(map[string]int)
	awardCnfEx:= cfg.Sign["AwardCnfEx"].(map[string]int)
	PropsName:= cfg.Sign["propsName"].(map[int]string)
	PropsNum:= cfg.Sign["propsNum"].(map[int]int16)
	propId:=awardCnfEx[dayIndex]
	propName:=PropsName[propId]
	propNum:=PropsNum[propId]
	if sendType>0{
		var userDepot = &user.UserDepot{
			AreaId:uint(areaId),
			PropName:propName,
			PropId:uint(propId),
			PropNum:propNum,
			UserId:uint(userId),
			DType:0,
			SType:1,
		}
		if err:=userDb.Create(userDepot).Error;err!=nil{
			log.Debug("sendProp:",err)
			return false,"发送奖品失败"
		}else{
			return true,"发送奖品失败"
		}
	}else{
		//发送能量
		userDb.Where(map[string]interface{}{"userId":userId,"areaId":areaId}).First(&userWealth)
		indexNum:=awardCnf[dayIndex]
		e:=userWealth.Energy+float64(indexNum)
		where:=map[string]interface{}{"userId":userId,"areaId":areaId}
		if err:=userDb.Model(&userWealth).Where(where).Update(map[string]interface{}{"energy":e}).Error;err!=nil{
			log.Debug("sendenergy:",err)
			return false,"发送能量失败"
		}else{
			return true,"发送能量成功"
		}
	}
}

//附近的好友列表(随机来10)
func (u *User) gmlist(session gate.Session,msg map[string]interface{})(result map[string]interface{}, err string) {
	var userDb = model.DB("FarmUser")
	defer userDb.Close()
	var users user.GameUser
	var usersResult []user.GameUserResult
	//var userWealth user.UserWealth
	selectStr:="userId,nickname,head,sex"
	sort:="lastLoginTime desc"
	var prepage int8=10
	var page int8=0
	where:=map[string]interface{}{}
	bm:=utils.GetPageList(userDb,&usersResult,&users,selectStr,where,sort,prepage,page,"game_user",false)
	return bm,""
}
//删除好友
func (u *User) deleteGm(session gate.Session,msg map[string]interface{})(result bool, err string) {
	var userDb = model.DB("FarmUser")
	defer userDb.Close()
	var gm user.UserGm
	userId:=msg["userId"].(float64)
	delUserId:=msg["delUserId"].(float64)
	areaId:=msg["areaId"].(float64)
	where:=map[string]interface{}{"userId":userId,"areaId":areaId}
	userDb.Where(where).First(&gm)

	var m []uint = nil
	json.Unmarshal(*gm.Fans,&m)
	for k,v:=range m{
		if v==uint(delUserId){
			kk := k + 1
			m = append(m[:k], m[kk:]...)
		}
	}
	m2,_:=json.Marshal(m)

	where2 := map[string]interface{}{"userId":userId,"areaId":areaId}
	if err:=userDb.Model(&gm).Where(where2).Update(map[string]interface{}{"fans":&m2}).Error;err!=nil{
		log.Debug("fans",err)
	}
	//fmt.Println(m)
	return true,""
}
//添加好友
func (u *User) addGm(session gate.Session,msg map[string]interface{})(result bool, err string) {
	var userDb = model.DB("FarmUser")
	defer userDb.Close()
	var gm user.UserGm
	userId:=msg["userId"].(float64)
	addUserId:=msg["addUserId"].(float64)
	areaId:=msg["areaId"].(float64)
	where:=map[string]interface{}{"userId":userId,"areaId":areaId}
	userDb.Where(where).First(&gm)
	var m []uint = nil
	json.Unmarshal(*gm.Fans,&m)
	m = append(m,uint(addUserId))
	m2,_:=json.Marshal(m)

	where2 := map[string]interface{}{"userId":userId,"areaId":areaId}
	if err:=userDb.Model(&gm).Where(where2).Update(map[string]interface{}{"fans":&m2}).Error;err!=nil{
		log.Debug("fans",err)
	}
	return true,""
}

func (u *User) addDepot(session gate.Session,msg map[string]interface{})(result bool, err string) {
	var userDb = model.DB("FarmUser")
	defer userDb.Close()
	areaId:=msg["areaId"].(float64)
	propName:=msg["propName"].(string)
	propId:=msg["propId"].(float64)
	propNum:=msg["propNum"].(float64)
	userId:=msg["userId"].(float64)
	sType:=msg["SType"].(float64)
	var userDepot = &user.UserDepot{
		AreaId:uint(areaId),
		PropName:propName,
		PropId:uint(propId),
		PropNum:int16(propNum),
		UserId:uint(userId),
		DType:1,
		SType:int8(sType),
	}
	if err:=userDb.Create(userDepot).Error;err!=nil{
		log.Debug("sendProp:",err)
		return false,"收获失败"
	}else{
		return true,"收获成功"
	}
	return true,""
}
func (u *User) signList(session gate.Session,msg map[string]interface{})(result map[string]interface{}, err string) {
	var userDb = model.DB("FarmConfig")
	var logDb = model.DB("FarmLog")
	defer userDb.Close()
	defer logDb.Close()
	areaId:=msg["areaId"].(float64)
	userId:=msg["userId"].(float64)
	var signCfg []config.SignCfg
	var results []config.SignCfg
	sort:="day Asc"
	var prepage int8=7
	var page int8=0

	selectStr:="id,propName,price,parPrice,info"
	var signLog gamelog.LogSign

	where2:=map[string]interface{}{"userId":userId,"areaId":areaId}
	if err:=logDb.Where(where2).First(&signLog).Error;err!=nil{
		return nil,"用户签到配置获取失败"
	}
	var gain int8 = 0
	if signLog.Gain!=0{
		gain = 1
	}
	where:=map[string]interface{}{"areaId":areaId,"gain":gain}
	ds:=utils.GetPageList(userDb,&results,&signCfg,selectStr,where,sort,prepage,page,"sign_cfg",false)

	return ds,""
}











